package com.android.aiod.utils;

import android.os.Environment;

import com.android.baselibrary.tool.Log;
import com.android.baselibrary.util.DateUtil;
import com.android.baselibrary.util.FileUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

public class LogUtil {
    public static void writerlog(String msg) {
        //日志根目录
        String rootPath = Environment.getExternalStorageDirectory() + "/AIOD/Log";
        FileWriter fw = null;
        BufferedWriter bw = null;
        String day = DateUtil.getDateFromTimeLine(System.currentTimeMillis(), "yyyy-MM-dd");
        String time = DateUtil.getDateFromTimeLine(System.currentTimeMillis());
        String hour = DateUtil.getDateFromTimeLine(System.currentTimeMillis(), "yyyy-MM-dd_HH");
        try {
            //创建文件夹
            File dir = new File(rootPath, day);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //创建文件
            File file = new File(dir, hour + ".txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            //写入日志文件
            fw = new FileWriter(file, true);
            bw = new BufferedWriter(fw);
            bw.write(time + ">>>" + msg + "\n");
            bw.close();
            fw.close();
            Log.i("写入日志");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            rootPath = null;
            fw = null;
            bw = null;
            day = null;
            time = null;
            hour = null;
        }
        deleteDIR();
    }

    //删掉3天前的目录
    private static void deleteDIR()
    {
        String rootPath = Environment.getExternalStorageDirectory() + "/AIOD/Log";
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-7);
        String day = DateUtil.getDateFromTimeLine(calendar.getTimeInMillis(), "yyyy-MM-dd");
        FileUtil.delete(rootPath+ "/"+ day);

        rootPath = null;
        calendar=null;
        day = null;
    }
}
